package com.atguigu.srb.core.controller.api;


import com.atguigu.srb.base.result.ResponseEnum;
import com.atguigu.srb.base.result.ResponseVo;
import com.atguigu.srb.base.util.JwtUtils;
import com.atguigu.srb.base.util.SrbAssert;
import com.atguigu.srb.core.pojo.entity.BorrowInfo;
import com.atguigu.srb.core.service.BorrowInfoService;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * <p>
 * 借款信息表 前端控制器
 * </p>
 *
 * @author Atguigu
 * @since 2023-03-25
 */
@RestController
@RequestMapping("/api/core/borrowInfo")
public class ApiBorrowInfoController {
    @Resource
    BorrowInfoService borrowInfoService;
    @ApiOperation("查询借款申请状态")
    @GetMapping("status")
    public ResponseVo status(@RequestHeader("token")String token){
        Integer status = borrowInfoService.getStatus(token);
        // 状态（0：未提交，1：审核中， 2：审核通过， -1：审核不通过 -2已撤销）
        // 未提交才会给会员展示借款申请表单
        return ResponseVo.ok().data("status",status);
    }
    @ApiOperation("撤销借款申请")
    @PutMapping("/my/cancel/{id}")
    public ResponseVo borrowCancel(@RequestHeader("token")String token,
                                   @PathVariable("id")Long id){
        Long userId = JwtUtils.getUserId(token);
        //校验借款申请的状态，只有待审核的才可以撤销
        boolean b = borrowInfoService.update(Wrappers.lambdaUpdate(BorrowInfo.class)
                .eq(BorrowInfo::getId, id)
                .eq(BorrowInfo::getUserId, userId)
                .eq(BorrowInfo::getStatus, 1) //查询登录的用户的指定的状态为待审核的借款信息
                .set(BorrowInfo::getStatus, -2));//更新状态为撤销状态
        SrbAssert.assertTrue(b , ResponseEnum.USER_BORROWINFO_STATUS_ERROR);
        return ResponseVo.ok().message("撤销成功");
    }
    @ApiOperation("查询借款记录列表")
    @GetMapping("/my/borrows/{pageNum}/{pageSize}")
    public ResponseVo myBorrows(@RequestHeader("token")String token,
                                @PathVariable("pageNum")Integer pageNum,
                                @PathVariable("pageSize")Integer pageSize){
        Page<BorrowInfo> page = new Page<>(pageNum,pageSize);
        borrowInfoService.getMyBorrows(page,token);
        return ResponseVo.ok().data("page",page);
    }
    @ApiOperation("借款申请")
    @PostMapping
    public ResponseVo save(@RequestBody BorrowInfo borrowInfo,
                           @RequestHeader("token")String token){
        borrowInfoService.saveApply(borrowInfo,token);
        return ResponseVo.ok();
    }
}

